<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车辆型号" prop="vehicleModel">
        <el-input
          v-model="queryParams.vehicleModel"
          placeholder="请输入车辆型号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车身颜色" prop="vehicleColor">
        <el-input
          v-model="queryParams.vehicleColor"
          placeholder="请输入车身颜色"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上线时间">
        <el-date-picker
          v-model="onlineDateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
<!--      <el-form-item label="上线时间" prop="onlineTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.onlineTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择上线时间">
        </el-date-picker>
      </el-form-item>-->
      <el-form-item label="上架时间">
        <el-date-picker
          v-model="saleDateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
<!--      <el-form-item label="上架时间" prop="saleTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.saleTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择上架时间">
        </el-date-picker>
      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['base:vehicle:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['base:vehicle:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['base:vehicle:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="vehicleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="车辆图片" align="center"  prop="vehicleImage">
        <template slot-scope="scope">
          <img :src="imgFormat(scope.row)" style="height: 100px;height: 100px">
        </template>
      </el-table-column>
      <el-table-column label="车身颜色" align="center" prop="vehicleColor" />
      <el-table-column label="车辆型号" align="center" prop="vehicleModel" />
      <el-table-column label="上线时间" align="center" prop="onlineTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.onlineTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上架状态" align="center" key="saleStatus" >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.saleStatus"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="上架时间" align="center" prop="saleTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.saleTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="累计销量" align="center" prop="saleCount" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['base:vehicle:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['base:vehicle:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改车型管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="车辆型号" prop="vehicleModel">
              <el-input v-model="form.vehicleModel" placeholder="请输入车辆型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车身颜色" prop="vehicleColor">
              <el-input v-model="form.vehicleColor" placeholder="请输入车身颜色" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="车辆图片">
<!--              <imageUpload v-model="form.vehicleImage"/>-->
              <el-upload
                action= "#"
                ref="upload"
                accept='image/gif,image/jpeg,image/jpg,image/png,image/svg'
                :auto-upload="false"
                :http-request="requestUpload"
                :multiple=true
                list-type="picture-card"
                :before-upload="beforeUpload"
                :on-change="handleChange"
                :file-list="fileList"
                :on-remove="handleRemove">
                <i class="el-icon-plus"></i>
              </el-upload>

            </el-form-item>
          </el-col>
<!--          <el-col :span="12">
            <el-form-item label="上线时间" prop="onlineTime">
              <el-date-picker clearable size="small"
                              v-model="form.onlineTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择上线时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上架时间" prop="saleTime">
              <el-date-picker clearable size="small"
                              v-model="form.saleTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择上架时间">
              </el-date-picker>
            </el-form-item>
          </el-col>-->
          <el-col :span="24">
            <el-form-item label="车辆介绍">
              <editor v-model="form.vehicleDescribe" :min-height="500"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listVehicle,
  getVehicle,
  delVehicle,
  addVehicle,
  updateVehicle,
  exportVehicle,
  uploadVehicleImage,
  changeSaleStatus
} from "@/api/base/vehicle";
import Editor from "@/components/Editor";

export default {
  name: "Vehicle",
  components: {
    Editor
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 日期范围
      onlineDateRange: [],
      // 日期范围
      saleDateRange: [],
      // 总条数
      total: 0,
      // 车型管理表格数据
      vehicleList: [],
      fileList:[],
      //车辆图片
      vehicleImageList:[],
      vehicleUpdateImage:[],
      vehicleDelImage:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        vehicleModel: null,
        vehicleColor: null,
        vehicleImage: null,
        saleStatus: null,
        onlineTime: null,
        saleTime: null,
        saleCount: null,
        vehicleDescribe: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        vehicleModel: [
          { required: true, message: "车辆型号不能为空", trigger: "blur" }
        ],
        vehicleColor: [
          { required: true, message: "车辆颜色不能为空", trigger: "blur" }
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询车型管理列表 */
    getList() {
      this.loading = true;
      listVehicle(this.addDateRanges(this.queryParams, this.onlineDateRange,this.saleDateRange)).then(response => {
        this.vehicleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    imgFormat(row){
      if(row.vehicleImage!=""){
        let img=row.vehicleImage.split(",")[0];
        return process.env.VUE_APP_BASE_API+img;
      }
      return row.vehicleImage
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        vehicleModel: null,
        vehicleColor: null,
        vehicleImage: '',
        saleStatus: null,
        onlineTime: null,
        saleTime: null,
        saleCount: null,
        vehicleDescribe: null,
        vehicleDelImage:[]
      };
      this.fileList=[];
      this.vehicleUpdateImage=[],
      this.vehicleDelImage=[],
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.onlineDateRange=[],
      this.saleDateRange=[],
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加车型管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getVehicle(id).then(response => {
        this.form = response.data;
        if(this.form.vehicleImage!=''){
          this.vehicleUpdateImage =this.form.vehicleImage.split(",")
          for (let i = 0; i <this.vehicleUpdateImage.length ; i++) {
            this.fileList.push({id:this.form.id,url:process.env.VUE_APP_BASE_API+this.vehicleUpdateImage[i]});
          }
        }
        this.open = true;
        this.title = "修改车型管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            //图片上传
            let imgForm = new FormData()
            this.vehicleImageList.forEach(file =>{
              imgForm.append("files",file.raw);
            });
            //重新组织字段
            this.form.vehicleImage='';
            for (let i = 0; i < this.vehicleUpdateImage.length; i++) {
              if(this.form.vehicleImage==''){
                this.form.vehicleImage=this.vehicleUpdateImage[i];
              }else {
                this.form.vehicleImage=this.form.vehicleImage+","+this.vehicleUpdateImage[i];
              }
            }
            //删除的图片
            this.form.vehicleDelImage=this.vehicleDelImage;
            uploadVehicleImage(imgForm).then(response => {
              if(this.form.vehicleImage=='' ){
                this.form.vehicleImage=response.imgUrl;
              }else {
                if(response.imgUrl!=''){
                  this.form.vehicleImage=this.form.vehicleImage+","+response.imgUrl;
                }
              }
              updateVehicle(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.fileList=[];
                this.getList();
              });
            });
          } else {
            //图片上传
            let imgForm = new FormData()
            this.vehicleImageList.forEach(file =>{
              imgForm.append("files",file.raw);
            });
            uploadVehicleImage(imgForm).then(response => {
              this.form.vehicleImage+= response.imgUrl;
              addVehicle(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.fileList=[];
                this.getList();
              });
            });
          }
        }
      });
    },
    // 上架状态修改
    handleStatusChange(row) {
      let text = row.saleStatus === "0" ? "上架" : "下架";
      this.$confirm('确认要"' + text + '该车型吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return changeSaleStatus(row.id, row.saleStatus);
      }).then(() => {
        this.getList();
        this.msgSuccess(text + "成功");
      }).catch(function() {
        row.saleStatus = row.saleStatus === "0" ? "1" : "0";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除车型管理编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delVehicle(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有车型管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportVehicle(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        })
    },
    handleChange(file, fileList) {
      this.vehicleImageList = fileList;
    },
    handleRemove(file, fileList) {
      this.vehicleDelImage.push(file.url);
      let index=this.vehicleUpdateImage.findIndex(item=> item === file.url)
      this.vehicleUpdateImage.splice(index, 1);
      this.vehicleImageList = fileList;
    },
    beforeUpload(param) {
      //对图片进行压缩
      const imgSize = param.size / 1024 / 1024
      const _this = this
      if(imgSize > 1) {
        return new Promise(resolve => {
          const reader = new FileReader()
          const image = new Image()
          image.onload = (imageEvent) => {
            const canvas = document.createElement('canvas');
            const context = canvas.getContext('2d');
            const width = image.width * _this.imgQuality
            const height = image.height * _this.imgQuality
            _this.imgWidthHeight = `${width}/${height}`
            //console.log(`图片上传前，压缩：${_this.imgWidthHeight}`)
            canvas.width = width;
            canvas.height = height;
            context.clearRect(0, 0, width, height);
            context.drawImage(image, 0, 0, width, height);
            const dataUrl = canvas.toDataURL(param.type);
            const blobData = _this.dataURItoBlob(dataUrl, param.type);
            resolve(blobData)
          }
          reader.onload = (e => { image.src = e.target.result; });
          reader.readAsDataURL(param);
        })
      } else {
        return new Promise(resolve => {
          const reader = new FileReader()
          const image = new Image()
          image.onload = (imageEvent) => {
            const width = image.width
            const height = image.height
            _this.imgWidthHeight = `${width}/${height}`
            //console.log(`图片上传前，不需要压缩：${_this.imgWidthHeight}`)
            resolve()
          }
          reader.onload = (e => { image.src = e.target.result; });
          reader.readAsDataURL(param)
        })
      }
    },
    // 覆盖默认的上传行为
    requestUpload() {
    },
  }
};
</script>

